const app = getApp()
var t = getApp().api;
var h = getApp().api,
  a = getApp();
Page({
  data: {
    cart_list: [],
    currentTab: 0,
    navScrollLeft: 0,
    cart_id: 0,
    page: 0,
    getPostsEnd: 0,
    vgoods_list: [],
    goods_one: 1,
    indicatorDots: false,
    autoplays: true,
    interval: 4000,
    circular: true,
    duration: 800,
    swiperCurrent: 0,
    banner_list: [],
    data: {},
    isIphoneX:false,
    state: -1,
    vgoods_left_list:[],
    vgoods_right_list: []
  },
  //事件处理函数
  onLoad: function() {
    var that = this;
    wx.getStorage({
      key: 'good_vgoods',
      success(res) {

      },
    })
    that.data.query = wx.createSelectorQuery();
    that.data.select = that.data.query.selectAll('#left-col-inner, #right-col-inner');
    getApp().page.onLoad(this, t);
    that.getPosts();
    this.themeColor()
  },
  swiperChange(e) {
    const that = this;
    that.setData({
      swiperCurrent: e.detail.current
    })
  }, 
  themeColor: function () {
    var cl = wx.getStorageSync('_navigation_bar_color').themeColor;
    var cl_b = !cl || cl == '#ffffff' ? '#ff4544' : cl;
    var color_rgb = this.hexToRgb(cl_b);
    var back_g = 'rgba(' + color_rgb.r + ',' + color_rgb.g + ',' + color_rgb.b + ',.5)'
    this.setData({
      all_color: cl ? cl : '#ffffff',
      back_g: back_g
      // back_end: back_end
    });
  },
  hexToRgb: function (hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null;
  },
  getPosts: function() {
    var that = this;
    if (that.data.getPostsEnd && that.data.page > 0) {
      return false;
    }
    wx.showLoading({
      title: '玩命加载中',
    })
    a.request({
      url: t.vgoods.list,
      method: "POST",
      data: {
        cart_id: that.data.cart_id,
        page: that.data.page
      },
      success: function(t) {
        wx.hideLoading()
        if (t.code == 0) {
          that.setData({
            getPostsEnd: t.data.vgoods_list.length < 15 ? 1 : 0,
            cart_list: t.data.cart_list,
            banner_list: t.data.banner_list,
            page: that.data.page + 1,
          })
          if (t.data.vgoods_list.length > 0) {
            var vgoods_list = that.xuanran_good(t.data.vgoods_list);
            return new Promise((resolve, reject) => {
              that._render(vgoods_list,0)
            })
          }
          
        }
      },
      complete: function() {
        wx.stopPullDownRefresh();
      }
    })
  },
  _render (element,i=0) {
    var that = this;
    that.data.select.boundingClientRect().exec(arr => {
      const rects = arr[0]
      const leftColHeight = rects[0].height
      const rightColHeight = rects[1].height
      var vgoods_left_list = that.data.vgoods_left_list;
      var vgoods_right_list = that.data.vgoods_right_list;
      if (leftColHeight <= rightColHeight) {
        vgoods_left_list = vgoods_left_list.concat(element[i]);
        that.setData({
          vgoods_left_list:vgoods_left_list
        },() => {
          ++i;
          if (element.length >i) {
            that._render(element,i)
          }
        })
      }else {
        vgoods_right_list = vgoods_right_list.concat(element[i]);
        that.setData({
          vgoods_right_list:vgoods_right_list
        },() => {
          ++i;
          if (element.length >i) {
            that._render(element,i)
          }
        })
      }
    });
  },
  xuanran_good: function(tt,ii=0) {
    var that = this;
    var good_vgoods = wx.getStorageSync('good_vgoods')
    if (good_vgoods) {
      for (var i = 0; i < tt.length; i++) {
        if (good_vgoods.indexOf(tt[i].id) > -1) {
          tt[i].good = 1
        } else {
          tt[i].good = 0
        }
      }
      return tt;
    }else {
      for (var i = 0; i < tt.length; i++) {
        tt[i].good = 0;
      }
      return tt;
    }
  },

  onShow: function() {
    //wx.hideTabBar()
    getApp().page.onShow(this);
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        if ((res.model.indexOf("X") >= 0 || res.model.indexOf("iPhone11") >= 0 ) && res.model.indexOf('iPhone') >= 0) {
          that.setData({
            isIphoneX: true
          })
        }
      }
    })
    if (this.data.cart_add_list == [] || this.data.cart_list == [] || this.data.vgoods_list == []){
      this.getPosts();
    }
    this.show_navs();
    this.cart_num();
    // that.xuanran_good(that.data.vgoods_list,1);
  },
  goodsQrcodeClick: function(t) {
    var a = t.currentTarget.dataset.src;
    var pid = t.currentTarget.dataset.pid;
    var image_arr = this.data.vgoods_list[pid].images;
    var urls = [];
    for (var value of image_arr){
      urls.push(value.feil_url)
    }
    wx.previewImage({
      current:a,
      urls: urls
    });
  },
  onReachBottom: function(t) {
    this.getPosts()
  },
  good_Y: function(tt) {
    if (!wx.getStorageSync('USER_INFO') || !wx.getStorageSync('USER_INFO').id > 0) {
      this.setData({
        user_info_show:!0
      })
      return false;
    }
    var posts_id = tt.currentTarget.dataset.id;
    var index = tt.currentTarget.dataset.index;
    var option = tt.currentTarget.dataset.option;
    var that = this;
    a.request({
      url: t.vgoods.good,
      method: "POST",
      data: {
        id: posts_id
      },
      success: function(t) {
        if (option == 'left') {
          var vgoods_left_list = that.data.vgoods_left_list;
          vgoods_left_list[index].good = 1;
          vgoods_left_list[index].good_num++;
          that.setData({
            vgoods_left_list: vgoods_left_list
          })
        }else {
          var vgoods_right_list = that.data.vgoods_right_list;
          vgoods_right_list[index].good = 1;
          vgoods_right_list[index].good_num++;
          that.setData({
            vgoods_right_list: vgoods_right_list
          })
        }
        wx.getStorage({
          key: 'good_vgoods',
          success(res) {
            res.data.push(posts_id);
            wx.setStorage({
              key: 'good_vgoods',
              data: res.data
            })
          },
          fail() {
            var arr = []
            arr.push(posts_id)
            wx.setStorage({
              key: 'good_vgoods',
              data: arr
            })
          }
        })
      }
    })
  },

  switchNav(event) {

    var that = this;
    that.setData({
      cart_id: event.currentTarget.dataset.id,
      page: 0,
      vgoods_right_list: [],
      vgoods_left_list: [],
      getPostsEnd:0
    })
    that.getPosts();
    var cur = event.currentTarget.dataset.current;
    //每个tab选项宽度占1/5
    var singleNavWidth = this.data.windowWidth / 5;
    //tab选项居中                            
    this.setData({
      navScrollLeft: (cur - 2) * singleNavWidth
    })
    if (this.data.currentTab == cur) {
      return false;
    } else {
      this.setData({
        currentTab: cur
      })
    }
  }, 
 

  show_navs: function() {
    var that = this;
    var nav = wx.getStorageSync("_navbar");
    var url = "/vgoods/index/index";
    for (var i = 0; i < nav.navs.length; i++) {
      if (nav.navs[i].url == url) {
        if (getApp().globalData.nav_index == i) {
          if (typeof that.getTabBar === 'function' &&
            that.getTabBar()) {
            that.getTabBar().setData({
              selected: getApp().globalData.nav_index,
              is_show: 1
            })
          }
        } else {
          getApp().globalData.nav_index = i;
          if (typeof that.getTabBar === 'function' &&
            that.getTabBar()) {
            that.getTabBar().setData({
              selected: getApp().globalData.nav_index,
              is_show: 1
            })
          }
        }
      }
    }
  },
  onPullDownRefresh: function() {
    wx.reLaunch({
      url: '/vgoods/index/index',
    })
  },
  // 获取购物车数量
  cart_num: function () {
    var that = this;
    wx.getStorage({
      key: 'user_info',
      success: function (res) {
        a.request({
          url: h.cart.list,
          success: function (t) {
            if (0 == t.code) {
              if (typeof that.getTabBar === 'function' &&
                that.getTabBar()) {
                if (t.data.mch_list.length > 0) {
                  var length = t.data.list.length + t.data.mch_list[0].list.length;
                } else {
                  var length = t.data.list.length
                }
                that.getTabBar().setData({
                  cart_num: length
                })
              }
            }
          }
        });
      },
    })
  },
  to_vgoods: function (event) {
    wx.navigateTo({
      url: '/vgoods/edit/index?id=' + event.currentTarget.dataset.id
    })
  }
 

})